using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Threading;



namespace ConsoleApplication1
{
    class Program
    {
        static Boolean _continue = true;
        static SerialPort sp;
        static string pong;

/*        public static void Read()
        {
            while (_continue)
            {
                try
                {
                    string message = sp.ReadLine();
                    Console.WriteLine(message);
                }
                catch (TimeoutException) { }
            }
        }
        */
        static int Main(string[] args)
        {
//            Thread readThread = new Thread(Read);
            string[] ports = new string[32];
            ports = scanPorts();
            bool found = false;


            if (ports.Length == 0)
                return -1;

                foreach (string comPort in ports)
                {
                    sp = new SerialPort();
                    if (comPort == null)
                        break;
                    sp.PortName = comPort;
                    sp.ReadTimeout = 1000;
                    sp.WriteTimeout = 1000;
                    int tries = 0;

                tryPort:
                    try
                    {
                        sp.Open();
                        //                readThread.Start();
                        sp.Write("p");
                        Console.WriteLine("Try #{0}:", tries);
                        pong = sp.ReadLine();
                        if (pong.Contains("o"))
                        {
                            Console.WriteLine("Ambient Trust Cube responded on {0}", comPort);
                            editConfig(comPort);
                            found = true;
                            break;
                        }
                        else
                        {
                            Console.WriteLine("Cube not on {0}.", comPort);
                        }
                    }
                    catch (TimeoutException e)
                    {
                        if (tries < 10)
                        {
                            tries++;
                            Console.WriteLine("Timeout #{0} on {1}", tries, comPort);
                            sp.Close();
                            goto tryPort;
                        }
                        else
                            continue;
                    }


                    if (!found)
                    {
                        Console.WriteLine("Could not find Ambient Trust. Please make sure it is plugged in.");
                        Console.WriteLine("Press any key to close this dialog...");
                        Console.ReadLine();
                        if (sp != null)
                            sp.Close();
                        return -1;
                    }

                    Console.WriteLine(pong);

                }
                //           Console.WriteLine("Configuration of Ambient Trust successful.");
                Console.WriteLine("Press any key to close this dialog...");
                Console.ReadLine();

                if (sp != null)
                    sp.Close();
                return (0);

        }
        static string [] scanPorts()
        {
            int i = 0;
            string[] ports = new string[32];

            ports = SerialPort.GetPortNames();

            if (ports.Length != 0)
                Console.WriteLine(" Available COM Ports Ambient Trust could potentially be on: ");
            else
            {
                Console.WriteLine(" Ambient Trust was not found. Please plug Ambient Trust in and rerun setup.");
                Console.ReadLine();
                if (sp != null)
                    sp.Close();
              //  return "-1";
            }

            foreach (string s in ports)
            {
                ports[i] = s;
                Console.WriteLine("   {0}", s);
                i++;
            }

            Console.WriteLine("  ");
            //Debug lines
            /*            foreach (string s in ports)
            {
                if (s != null)
                {
                    Console.WriteLine("     {0}", s);
                }
            }*/
            return ports;
        }
        static void editConfig(string comNumber)
        {
            StringBuilder newFile = new StringBuilder();

            string temp = "";

            string[] file = File.ReadAllLines(@"serproxy\serproxy.cfg");

            foreach (string line in file)
            {

                if (line.Contains("serial_device1"))
                {
                  
                    temp = line.Replace(line, string.Concat( "serial_device1=", comNumber ) );

                    newFile.Append(temp + "\r\n");

                    continue;

                }

                newFile.Append(line + "\r\n");

            }

            File.WriteAllText(@"serproxy\serproxy.cfg", newFile.ToString());
        }
    }
}
